<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
  <title>视频播放</title>
  <link rel="stylesheet" href="./css/local.css" />
  <script src="./js/player.js"></script>
</head>
<body>
  <div id='app'>
    <div class="navbar">
      <div class="navbar__placeholder" :style="`height: ${safe + 44}px`"></div>
      <div class="navbar--fixed">
        <div class="safe" :style="`height: ${safe}px`"></div>
        <div class="navbar__content">
          <div class="navbar__content__left" @click="goBack">
            <img src="./img/back.png" alt="" />
          </div>
          <div class="navbar__content__title">视频播放</div>
          <div class="uv-navbar__content__right"></div>
        </div>
      </div>
    </div>
    <div id="player"></div>
    <div class="box" :style="`height: calc(${44 + safe + 230}px)`">
      <div class="bigTitle">{{ detail.title }}</div>
      <div class="des">已更新{{ sub.all }}讲 | 已学完{{ sub.fish }}讲</div>
      <div class="gost">
        <div class="item" :class="{active: current == 0}" @click="current = 0">
          <img src="./img/nt1.png" class="ke1 ke img1" v-if="current == 0">
          <img src="./img/nt1-1.png" class="ke1 ke img2" v-else>
          <div class="font">播放目录</div>
        </div>
        <div class="item" :class="{active: current == 1}" @click="current = 1">
          <img src="./img/nt2.png" class="ke2 ke img1" v-if="current == 1">
          <img src="./img/nt2-2.png" class="ke2 ke img2" v-else>
          <div class="font">讲义</div>
        </div>
      </div>
      <div class="list" v-if="current == 0">
        <div class="item" v-for="(item, index) in lines" :key="index">
          <div class="title">{{ item.name }}</div>
          <template v-if="item.sections && item.sections.length">
            <div class="nst" v-for="(dt, idx) in item.sections" :key="idx" @click="toPlay(dt)">
              <div class="icon"><img src="./img/nt2-2.png" class="img"></div>
              <div class="right" v-if="play">
                <div class="name line1" :class="{ not: dt.percentage >= 90, red: play.id == dt.id }">{{ dt.name }}</div>
                <div class="desc">
                  时长{{ dt.video_duration }} <template v-if="dt.percentage >= 90"> | 已学完</template>
                  <div class="nowPlay" v-if="play.id == dt.id">正在播放</div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div class="list" v-if="current == 1">
        <div class="item" v-for="(item, index) in lines" :key="index">
          <div class="title">{{ item.name }}</div>
          <template v-if="item.sections && item.sections.length">
            <div class="nst" v-for="(dt, idx) in item.sections" :key="idx" @click="downFile(dt)">
              <div class="icon"><img src="./img/Handouts.png" class="img"></div>
              <div class="right">
                <div class="name" :class="{ not: !dt.pdf_url }">{{ dt.name }}</div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
  <script src="./js/hybrid_html_uni.webview.1.5.5.js"></script>
  <script src="./js/vue2.js"></script>
  <script src="./js/jquery.js"></script>
  <script src="./js/axios.js"></script>
  <script>
    document.addEventListener('UniAppJSBridgeReady', function(){
      var app2 = new Vue({
        el: '#app',
        data: {
          id: '',
          safe: plus.navigator.getStatusbarHeight() || 0,
          token: plus.storage.getItem('token') || '',
          current: 0,
          play: null,
          option: {},
          detail: '',
          sub: {
            fish: 0,
            all: 0
          },
          lines: [],
          playList: [],
          player: null
        },
        mounted() {
          plus.navigator.setStatusBarStyle('dark');
          uni.getEnv(function(res) {
            console.log('当前环境：' + JSON.stringify(res));
          });
          window.myAjax = (data) => {
            console.log(JSON.stringify(data));
            axios.defaults.baseURL = data.baseURL;
            axios.defaults.headers['Content-Type'] = 'application/json; charset=utf-8';
            axios.defaults.headers['token'] = this.token;
            this.id = data.id;
            this.getData(this.id);
            this.getOutLine(this.id);
          }
        },
        methods: {
          getData(id){
            axios.get('/api/lesson/getLessonDetails', { params: { lessonId: id } }).then(res => {
              if(res.data.code == 1){
                const data = res.data.data;
                this.detail = data;
              }
            })
          },
          getOutLine(id){
            axios.get('/api/lesson/getLessonOutline', { params: { lessonId: id } }).then(res => {
              if(res.data.code == 1){
                const data = res.data.data;
                this.lines = data;
                if(data.length){
                  data.forEach(e => {
                    if(e.sections.length){
                      e.sections.forEach(a => {
                        this.playList = [...this.playList, a];
                        if(a.percentage >= 90){
                          this.sub.fish++;
                        }
                        if(!this.play){
                          this.play = a;
                        }
                      })
                    }
                  })
                }
                this.sub.all = this.playList.length;
                
                let storage = plus.storage.getItem('playStorage');
                if(storage){
                  const p = JSON.parse(storage);
                  if(p[this.id]){
                    this.play = p[this.id];
                  }
                }
                console.log(JSON.stringify(this.play));
                this.option = {
                  wrap: '#player',
                  width: '100%',
                  height: 230,
                  autoplay: true,
                  loading_bg_img: this.play.thumb,
                  vid: this.play.polyv_id,
                  webPageFullScreen: true,
                  fullScreenOrientation: 'landscape',
                  watchStartTime: (this.play.percentage / 100 * calculateTotalSeconds(this.play.video_duration)).toFixed(0)
                }
                this.player = polyvPlayer(this.option);
                const that = this;
                this.player.on('s2j_onPlayOver', () => {
                  console.info('视频播放完毕，通知uniapp切换下一个视频');
                  that.setCope(id);
                  that.nextPlay().then(res => {
                    console.log(that.option.vid);
                    that.player.changeVid(that.option);
                  })
                });
                setInterval(() => {
                  let tim = that.player.j2s_getCurrentTime();
                  if(tim){
                    this.schedule(tim);
                  }
                }, 3000)
              }
            })
          },
          setCope(id){
            axios.get('/api/lesson/getLessonOutline', { params: { lessonId: id } }).then(res => {
              if(res.data.code == 1){
                const data = res.data.data;
                this.lines = data;
              }
            })
          },
          // 手动切换视频
          toPlay(row){
            if(row.polyv_id){
              this.play = this.deepClone(row);
              this.option.vid = this.play.polyv_id;
              if(this.play.percentage){
                this.option.watchStartTime = (this.play.percentage / 100 * calculateTotalSeconds(this.play.video_duration)).toFixed(0);
              }else{
                this.option.watchStartTime = 0;
              }
              this.player.changeVid(this.option);
            }
          },
          // 上报播放进度
          reportLessonHistory(num){
            const params = {
              lessonId: this.id,
              lessonSection: this.play.id,
              percentage: num
            }
            axios.post('/api/lesson/reportLessonHistory', params).then(res => {
              if(res.data.code == 1){
              }
            })
          },
          // 获取下一个视频的信息，并将信息保存到当前页面全局option；
          nextPlay(){
            return new Promise((resolve, reject) => {
              let index = this.playList.findIndex(o => o.id == this.play.id);
              let obj = this.playList[index + 1];
              if(obj){
                this.play = this.deepClone(obj);
                this.option.vid = this.play.polyv_id;
                if(this.play.percentage){
                  this.option.watchStartTime = (this.play.percentage / 100 * calculateTotalSeconds(this.play.video_duration)).toFixed(0);
                }else{
                  this.option.watchStartTime = 0;
                }
                resolve();
              }
            })
          },
          // 深度克隆
          deepClone(obj, cache = new WeakMap()) {
          	if (obj === null || typeof obj !== 'object') return obj;
          	if (cache.has(obj)) return cache.get(obj);
          	let clone;
          	if (obj instanceof Date) {
          		clone = new Date(obj.getTime());
          	} else if (obj instanceof RegExp) {
          		clone = new RegExp(obj);
          	} else if (obj instanceof Map) {
          		clone = new Map(Array.from(obj, ([key, value]) => [key, this.deepClone(value, cache)]));
          	} else if (obj instanceof Set) {
          		clone = new Set(Array.from(obj, value => this.deepClone(value, cache)));
          	} else if (Array.isArray(obj)) {
          		clone = obj.map(value => this.deepClone(value, cache));
          	} else if (Object.prototype.toString.call(obj) === '[object Object]') {
          		clone = Object.create(Object.getPrototypeOf(obj));
          		cache.set(obj, clone);
          		for (const [key, value] of Object.entries(obj)) {
          			clone[key] = this.deepClone(value, cache);
          		}
          	} else {
          		clone = Object.assign({}, obj);
          	}
          	cache.set(obj, clone);
          	return clone;
          },
          // 监听播放进度
          schedule(tim){
            const storage = plus.storage.getItem('playStorage');
            let obj = {};
            if(storage){
              obj = JSON.parse(storage);
            }else{
              obj = {};
            }
            let totalTime = calculateTotalSeconds(this.play.video_duration);
            let currentTime = (tim / totalTime * 100).toFixed(1);
            
            this.play.percentage = currentTime;
            obj[this.id] = this.play;
            plus.storage.setItem('playStorage', JSON.stringify(obj));
            // console.log(JSON.stringify(obj));
            this.reportLessonHistory(currentTime);
          },
          downFile(row){
            uni.postMessage({
              data: {
                downFile: row,
              }
            })
          },
          goBack(){
            uni.navigateBack({
              delta: 1
            });
          }
        }
      })
      // 根据时长计算总秒数
      function calculateTotalSeconds(timeString) {
        const [hours, minutes, seconds] = timeString.split(':').map(Number);
        return hours * 3600 + minutes * 60 + seconds;
      }
      // let player = polyvPlayer({
      //   wrap: '#player',
      //   width: '100%',
      //   height: 230,
      //   autoplay: true,
      //   vid: 'aa1f360763b916625569ada992014728_a',
      //   webPageFullScreen: true,
      //   fullScreenOrientation: 'landscape',
      // });
      
      // var player = null;
      // window.myAjax = (data) => {
      //   player = polyvPlayer(data);
        // player.on('s2j_onPlayOver', () => {
        //   console.info('视频播放完毕，通知uniapp切换下一个视频');
          // uni.postMessage({
          //   data: {
          //     finish: true,
          //   }
          // })
        // });
      // }
      // // 切换下一个视频
      // window.myNext = (data) => {
      //   player.changeVid(data);
      // }
      // // 监听当前播放进度
      // setInterval(() => {
      //   let tim = player.j2s_getCurrentTime();
      //   if(tim){
      //     uni.postMessage({
      //       data: {
      //         times: tim,
      //       }
      //     })
      //   }
      // }, 3000)
    })
    
  </script>
</body>
</html>